/*
 * @Author: yao
 * @Date: 2024-11-12 08:59:32
 * @LastEditTime: 2024-11-19 15:37:58
 * @LastEditors: yao
 * @Description:
 * @FilePath: \jdev-web\src\stores\modules\user.ts
 */
import { defineStore } from "pinia";
import type { LoginParams } from "..";
import { getAppMenus, getUserResources, login } from "@/api/user";
import { ErrorMsg } from "@/components/Toast";
import { getToken, setToken } from "@/utils/utils";
import Storage from "@/utils/storage";
import config from "@/config/index";
import router from "@/router";
import { generatorDynamicRouter } from "@/router/generator-router";

const parseRoleModule = () => {
  let modulesList = Storage.get(config.RESOS_KEY);
  let modules: any = [];
  modulesList.forEach((item: any) => {
    if (item.systemId == config.SYSTEM.ID && item.moduleId) {
      modules.push(item.moduleId);
    }
  });
  return modules;
};
export const useUserStore = defineStore("user", {
  state: () => {
    return {
      userInfo: Storage.get("USERINFO"),
      token: getToken,
      roles: Storage.get("ROLES"),
      auths: [],
      modules: Storage.get("MODULES"),
      menus: [],
    };
  },
  actions: {
    async RESET_USER_STATE() {
      this.$reset();
    },
    async loginHandler(params: LoginParams) {
      const res = await login(params);
      if (!res || !res.success) {
        ErrorMsg(res.message || "登录失败");
        return res;
      }
      setToken(res.data.userToken);
      this.token = res.data.userToken;
      this.roles = res.data.userRoles;
      // 采集关键用户信息
      this.userInfo = {
        userName: res.data.userName,
        userId: res.data.id,
        userAccount: res.data.userAccount,
        orgName: res.data.userOrgName,
        orgId: res.data.userOrgId,
        groupTag: res.data.groupTag,
      };
      Storage.set("USERINFO", this.userInfo);
      Storage.set("ROLES", this.roles);
      return res.data;
    },
    async getResources() {
      const resources = await getUserResources({
        roles: this.roles.map((item: any) => item.roleId),
      });
      if (resources.success) {
        Storage.set(config.RESOS_KEY, resources.data.data);
        getAppMenus({
          systemId: config.SYSTEM.ID,
          modules: parseRoleModule(),
          DSOT: '{"sort":"ASC"}',
        }).then(async (res) => {
          if (res.success) {
            Storage.set("MODULES", res.data);
            const mData: any = await this.GenerateRoutes(
              Storage.get("MODULES")
            );
            mData.forEach((route: any) => {
              router.addRoute(route);
            });
          }
        });
      }
    },
    async GenerateRoutes(data: any) {
      return new Promise((resolve, reject) => {
        generatorDynamicRouter(data)
          .then((routers: any) => {
            resolve(routers);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    setRoutes(routes: any) {
      this.menus = routes;
      Storage.set("MENUS", routes);
    },
  },
});
